package com.mx.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

import org.apache.hadoop.fs.Path;

import com.mx.fs.FileInfo;
import com.mx.fs.utils.FSUtil;

/**
 * 
 * @author miao Ther socket server to receive a file from client and then store
 *         it into hdfs system. Using java NIO.
 */

public class Server {

	private static final int PORT = 8888;
	private Selector selector = null;
	private int i = 0;

	public Server() {
		try {
			selector = Selector.open();
			ServerSocketChannel serverSocketChannel = ServerSocketChannel
					.open();
			serverSocketChannel.socket().bind(new InetSocketAddress(PORT)); // port
			serverSocketChannel.configureBlocking(false);
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);// register
			while (true) {
				// selector 线程。select() 会阻塞，直到有客户端连接，或者有消息读入
				selector.select();
				Iterator<SelectionKey> iterator = selector.selectedKeys()
						.iterator();
				while (iterator.hasNext()) {

					SelectionKey selectionKey = iterator.next();
					iterator.remove(); // 删除此消息

					// 并在当前线程内处理。（为了高效，一般会在另一个线程中处理此消息，例如使用线程池等）
					handleSelectionKey(selectionKey);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void handleSelectionKey(SelectionKey selectionKey)
			throws IOException {
		ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
		SocketChannel sc = ssc.accept();
		FSUtil.store(sc, new FileInfo());
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Server();
//		FSUtil.deleteFolder(new Path("/"), false);
		
	}

}
